<script lang="ts" setup>
import { cloneDeep, pick } from '@peng_kai/kit/libs/lodash-es';
import { override } from '@peng_kai/kit/utils';
import CommissionShare from '~comp-b/referral/commission/CommissionShare.vue';

type TChannelDetail = NonNullable<Api.GetData<typeof apis.apiInviteChannelDetail>>;

const props = defineProps<{
  detail?: TChannelDetail;
  loading?: boolean;
}>();
const emits = defineEmits<{
  confirm: [typeof form.stateTF];
}>();

const appStore = useAppStore();
const { inviteStats, inviteStatsQry } = queries.useInviteStatisticsQuery();
const commissionsShares = ref([] as TChannelDetail['commission_shares']);
watchEffect(() => {
  commissionsShares.value = cloneDeep(props.detail
    ? props.detail.commission_shares ?? []
    : (inviteStats.value?.commission_shares ?? []).map(x => ({ ...x, shares: 0 })),
  );
});

const form = useAntdForm({
  name: {
    value: '',
    rules: [
      { required: true, type: 'string', message: $t('nrRgwVcSf5c5rbLXbCyFe') },
    ],
  },
  referral_code: {
    value: '',
    rules: [
      { required: true, type: 'string', min: 5, message: $t('lOs5Hqdmt3mPa1h4Czk4b') },
    ],
  },
  is_default: {
    value: false,
  },
}, {
  transform: state => ({
    ...state,
    is_default: Number(state.is_default),
  }),
});
watch(() => props.detail, (detail) => {
  detail && override(form.state, detail, { is_default: !!detail.is_default });
}, { immediate: true });

const currentInviteUrl = computed(() => {
  const code = form.state.referral_code;
  const tgBotName = appStore.handshake?.telegram_bot.username;
  const webName = appStore.handshake?.domain.www;

  return [code ? `https://t.me/${tgBotName}?start=${code}` : '', code ? `${webName}/?ic=${code}` : ''];
});

async function confirm() {
  try {
    await form.$form.validate?.();
    const state = {
      ...cloneDeep(form.stateTF),
      commissions_shares: commissionsShares.value.map(x => pick(x, ['category_id', 'game_id', 'shares'])),
    };

    emits('confirm', state);
  }
  catch (e) {
    // console.log(e);
  }
}
</script>

<template>
  <div>
    <!-- 分成比例 -->
    <TCard class="mb-4" icon="i-local:compaign_3" :title="$t('bblXesmCulWv0GyYrU4Gy')">
      <TSuspenseView
        v-bind="buildSvPropsOfQuery(inviteStatsQry)"
        class="grid grid-cols-2 gap-2" nonSuccessClass="col-span-full !p0"
      >
        <CommissionShare
          v-for="item of commissionsShares" :key="item.category_id"
          v-model:value="item.shares" class="last:odd:col-span-2"
          :class="{ 'op-50 pointer-events-none': loading || inviteStatsQry.isLoading.value }"
          :name="item.game_name" :coefficient="item.coefficient" :maxCommission="item.commissions"
        />
      </TSuspenseView>
    </TCard>

    <!-- 基本信息 -->
    <TCard icon="i-local:compaign_2" :title="$t('c6dXySeOgYetQCa724xJq')">
      <AForm v-bind="form.props" class="ant-cover__Form-compact" layout="vertical" hideRequiredMark :disabled="props.loading">
        <AFormItem v-bind="form.itemProps.name" :label="$t('cnbWGq4PuUxb3Joqjk6tS')">
          <TAntdTheme component="Input" theme="light">
            <AInput v-model:value="form.state.name" :placeholder="$t('nrRgwVcSf5c5rbLXbCyFe')" />
          </TAntdTheme>
        </AFormItem>

        <AFormItem v-bind="form.itemProps.referral_code" :label="$t('xyBc6p8NcXZme26ZMocNe')">
          <TAntdTheme component="Input" theme="light">
            <AInput
              v-model:value="form.state.referral_code" :disabled="detail && !!detail.referral_code"
              :placeholder="$t('lOs5Hqdmt3mPa1h4Czk4b')"
            />
          </TAntdTheme>
          <template v-if="currentInviteUrl" #extra>
            <div class="mt-2 flex gap-2">
              <span class="mr-auto text-sys-text-body">{{ $t('nUj0W3DPxcotAmoLfyk') }}: </span>
              <div class="flex-1 break-all text-sys-text-head">
                <p>
                  {{ currentInviteUrl[0] }}
                </p>
                <p>{{ currentInviteUrl[1] }}</p>
              </div>
            </div>
          </template>
        </AFormItem>

        <AFormItem v-bind="form.itemProps.is_default">
          <ACheckbox
            v-model:checked="form.state.is_default"
            :disabled="loading || (detail && !!detail?.is_default)"
          >
            {{ $t('yPq7iRvGdtKoPrIfXmYG') }}
          </ACheckbox>
          <THelptip overlayClassName="text-xs">
            {{ $t('zCVgQdekXwNtv2kVkkoB') }}
          </THelptip>
        </AFormItem>
      </AForm>
    </TCard>

    <AButton
      type="primary" class="ant-cover__Button-3d-primary mt-4"
      block :disabled="loading" :loading="loading"
      @click="confirm()"
    >
      {{ $t('dqcvMmkkLelXhEb_6QHcN') }}
    </AButton>
  </div>
</template>
